package com.tc.infinitechat.authenticationservice.utils.jwt;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tc.infinitechat.authenticationservice.constants.jwt.JwtTokenConstants;
import com.tc.infinitechat.authenticationservice.constants.jwt.TimeOutEnum;
import com.tc.infinitechat.authenticationservice.utils.sms.AliyunAccessKeyProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.time.Duration;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName JwtUtil
 * @Author 大马鲛鱼丸Gaga
 * @Description TODO
 * @Date 2025/10/8 20:58
 */
public class JwtUtil {
    // 生成JWT
    private final static Duration expiration = Duration.ofHours(TimeOutEnum.JWT_TIME_OUT.getTimeOut());
    public static String generate(String userId) {
        Date expiryDate = new Date(System.currentTimeMillis() + expiration.toMillis());
        return Jwts.builder()
                .setSubject(userId).setIssuedAt(new Date())
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, JwtTokenConstants.tokenSecretKey)
                .compact();
    }
    // 解析JWT
    public static Claims parse(String token) throws JwtException {
        if (StringUtils.isEmpty(token)){
            throw new JwtException("token 为空");
        }

        // 这个Claims对象包含了许多属性，比如签发时间、过期时间以及存放的数据等
        Claims claims = null;
        // 解析失败了会抛出异常，所以我们要捕捉一下。token过期、token非法都会导致解析失败
        claims = Jwts.parser()
                .setSigningKey(JwtTokenConstants.tokenSecretKey) // 设置秘钥
                .parseClaimsJws(token)
                .getBody();

        return claims;
    }
}
